package com.code.lightning.commander;

import com.beust.jcommander.JCommander;
import com.code.lightning.GeneratorHelper;
import com.code.lightning.code.base.BasicDBConnect;
import com.code.lightning.common.exception.LightingGeneratorException;
import com.code.lightning.config.BasicGeneratorConfig;
import com.code.lightning.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.sql.Connection;

/**
 * 命令行
 * @author LGX_TvT
 * @date 2021-01-31 21:57
 */
@Slf4j
public class CommandMain {

    public static void main(String[] argv) throws IOException {
        Command cli = new Command();
        JCommander jc = JCommander.newBuilder()
                .programName("Welcome to LightingGenerator " + CommandConfig.VERSION + " !!!")
                .addObject(cli)
                .build();
        jc.parse(argv);
        run(jc, cli);

    }

    public static void run(JCommander jc, Command command) {
        if (command.isHelp()) {
            jc.usage();
            return;
        }
        if (!StringUtils.isNotBlank(command.getConfig()) || !new File(command.getConfig()).exists()) {
            log.error("请输入正确的配置文件路径！");
            return;
        }

        BasicGeneratorConfig config = null;
        try {
            InputStream is = new FileInputStream(new File(command.getConfig()));
            config = PropertiesUtil.getConfig(is);
            BasicDBConnect.init(config);
            Connection connect = BasicDBConnect.getConnect();
            if (connect != null) {
                log.info("初始化配置文件成功!");
                log.info("测试连接数据库:" + connect + " SUCCESS!");
            }
            BasicDBConnect.close(connect, null, null);
        } catch (FileNotFoundException e) {
            log.error("请输入正确的配置文件！");
            e.printStackTrace();
            return;
        }

        if (command.isGenerator()) {
            GeneratorHelper generatorHelper = GeneratorHelper.getInstance(config);
            try {
                generatorHelper.generatorFile();
                return;
            } catch (LightingGeneratorException e) {
                e.printStackTrace();
            }
        }

        if (command.isSqlCli()) {
            try {
                new SqlCommandFunction().run();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
